/**
 * Created by songjuxi on 2017/3/29.
 */
import { connect } from 'react-redux';
import React, {Component} from 'react';

import { load } from './redux';
import Loadable from 'react-loadable';

function Loading(props) {
  if (props.error) {
    return <div>Error!</div>;
  } else if (props.pastDelay) {
    return <div>Loading...</div>;
  } else {
    return null;
  }
}

/**
 * components : 组件数据源
 */
@connect(state => ({ components: state.dyComponents }), { load })

export default class InvoiceOperatingViewWrap extends Component{
  constructor(props){
    super(props);
    this.state = {
      components: props.components || null
    };
  }

  componentDidMount() {
    console.log("only browser run this");
    // 加载组件
    this.props.load().then(() => {
      this.setState({
         components: this.loadInstance()
      })
    });
  }

  /**
   * 加载动态组件
   */
  loadInstance = () => {
    var {components = {}} = this.props.components||{};
    let location = this.props.location;
    var instances = {};
    Object.keys(components).map((hook)=>{
      components[hook].map((value)=>{
        // 组件名称
        var componentName = value["name"];
        var Ins = Loadable({
          loader: () => import(`../DynamicLoad/${componentName}/${componentName}`).then(object => object.default),
          loading: Loading,
          delay: 3000,
          render(loaded) {
            let Component = loaded;
            let props = value["config"];
            return <Component {...props} location = {location}/>;
          }
        });
        instances[hook] = instances[hook] || [];
        instances[hook].push(Ins);
      });
    });

    return instances;
  }

  render(){
    return (
     <div data-id="HOOK_InvoiceOpereatingViewWrap">
          {
            (this.state.components && this.state.components.HOOK_InvoiceOpereatingViewWrap||[]).map((Component,i)=>{
                return <Component key={i} />
            })
          }
      </div>
    )
  }
}